package com.example.gulimall.order.config;

import cn.hutool.core.util.StrUtil;
import com.example.common.constant.AuthServerConstant;
import com.example.common.constant.FeignConstant;
import com.example.common.constant.UriMatcherConstant;
import com.example.common.entity.member.MemberEntity;
import com.example.common.utils.GuLiMallThreadLocalPool;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Objects;

/**
 * <p>
 *
 * </p>
 *
 * @author zyred
 * @since v 0.1
 **/
@Configuration
public class LoginUserInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) throws Exception {

        final HttpSession session = request.getSession();
        MemberEntity memberEntity = (MemberEntity) request.getSession()
                .getAttribute(AuthServerConstant.SESSION_LOGIN_KEY);

        String sign = request.getHeader(FeignConstant.SIGN_KEY);

        String uri = request.getRequestURI();

        // 优先检查 session，将当前用户塞到线程中
        if (Objects.nonNull(memberEntity)) {
            GuLiMallThreadLocalPool.setMember(memberEntity);
            return true;
        }
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        boolean match = antPathMatcher.match(AuthServerConstant.MEMBER_ORDER, uri);
        boolean pay = antPathMatcher.match(AuthServerConstant.PAY_CALLBACK_PREFIX, uri);
        // 从支付宝请求回来的，不携带 sign
        if ((match || pay) && StrUtil.isBlank(sign)) {
            return true;
        }

        // 最后再来校验只有 sign 的情况
        if (StrUtil.isNotBlank(sign)) {
            return true;
        }

        session.setAttribute("msg", "您还未登录，请先登录!");
        response.sendRedirect("http://auth.gulimall.com/login.html");
        return false;
    }


    @Override
    public void postHandle(HttpServletRequest request,
                           HttpServletResponse response,
                           Object handler,
                           ModelAndView modelAndView) throws Exception {
        GuLiMallThreadLocalPool.removeMember();
    }
}
